package com.chain.BrotherExchange.utils;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 广告轮播
 */
public class CycleAdverts implements LifecycleObserver {

    private boolean isStart;
    private Handler mHandler;
    private Timer mCycleTimer;
    private int interval = 3000;
    private final RecyclerView mRecyclerView;
    private int currentPosition = Integer.MAX_VALUE / 2;

    public CycleAdverts(RecyclerView recyclerView) {
        mRecyclerView = recyclerView;
        mCycleTimer = new Timer();
        mHandler = new Handler(Looper.myLooper());
    }

    public void start() {
        isStart = true;
        Runnable runnable = () -> mRecyclerView.smoothScrollToPosition(++currentPosition);

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.post(runnable);
            }
        };

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View childViewUnder = recyclerView.findChildViewUnder(dx, dy);
                if (childViewUnder != null) {
                    int scrollPosition = recyclerView.getChildAdapterPosition(childViewUnder);
                    if (scrollPosition > 0) {
                        currentPosition = scrollPosition;
                    }
                }
            }
        });

        mCycleTimer.schedule(timerTask, interval, interval);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void onResume() {
        if (!isStart) {
            Runnable runnable = () -> mRecyclerView.smoothScrollToPosition(++currentPosition);

            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    mHandler.post(runnable);
                }
            };

            mCycleTimer.schedule(timerTask, interval, interval);
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void onPause() {
        if (mCycleTimer != null) {
            mCycleTimer.cancel();
            mCycleTimer.purge();
            mCycleTimer = null;
            mCycleTimer = new Timer();
            isStart = false;
        }
    }
}
